"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : gs_dump
Case Name   : 初始用户名中带大写，备份恢复函数、存储过程
Create At   : 2023.1.18
Owner       : @haomeng802
Description :
    1、创建mysql兼容数据库1
    2、兼容数据库1中创建用户1
    3、创建mysql兼容数据库
    4、兼容数据库2中创建用户2
    5、兼容数据库1中创建表,插入数据,创建存储过程
    6、执行gs_dump备份,备份用户1,备份库1,备份格式为自定义归档格式
    7、执行gs_restore恢复,恢复用户2,恢复库2
    8、清理环境
Expect      :
    1、创建库1成功
    2、创建用户1成功
    3、创建库2成功
    4、创建用户2成功
    5、创建表成功，插入数据成功，创建存储过程成功
    6、备份成功
    7、恢复成功
    8、清理环境成功
History     :
"""

import os
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class WDR(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.sh_pri = CommonSH('PrimaryDbUser')
        self.user_node = Node('PrimaryDbUser')
        self.constant = Constant()
        self.db_name1 = 'db_gs_dump_0130_1'
        self.db_name2 = 'db_gs_dump_0130_2'
        self.user_name1 = 'u_gs_dump_0130_1'
        self.user_name2 = 'u_gs_dump_0130_2'
        self.table = 't_gs_dump_0130'
        self.procedure = 'pro_gs_dump_0130'
        self.back_path = os.path.join(macro.DB_INSTANCE_PATH,
                                      'gs_dump_0130.dmp')

    def test_gs_dump(self):
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        text = '-----step1:创建mysql兼容数据库1;expect:创建成功-----'
        self.log.info(text)

        db1 = f'''drop database if exists {self.db_name1};
            create database {self.db_name1} with dbcompatibility='B';'''
        create_db1 = self.sh_pri.execut_db_sql(db1, dbname='postgres')
        self.log.info(create_db1)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, create_db1,
                      '执行失败' + text)

        text = '-----step2:兼容数据库1中创建用户1;expect:创建成功-----'
        self.log.info(text)

        user1 = f'''drop user if exists {self.user_name1} cascade;
            create user {self.user_name1} with sysadmin 
            password '{macro.COMMON_PASSWD}';'''
        create_user1 = self.sh_pri.execut_db_sql(user1,
                                                 dbname=f'{self.db_name1}')
        self.log.info(create_user1)
        self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG, create_user1,
                      '执行失败' + text)

        text = '-----step3:创建mysql兼容数据库2;expect:创建成功-----'
        self.log.info(text)

        db2 = f'''drop database if exists {self.db_name2};
            create database {self.db_name2} with dbcompatibility='B';'''
        create_db2 = self.sh_pri.execut_db_sql(db2, dbname='postgres')
        self.log.info(create_db2)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, create_db2,
                      '执行失败' + text)

        text = '-----step4:兼容数据库2中创建用户2;expect:创建成功-----'
        self.log.info(text)

        user2 = f'''drop user if exists {self.user_name2} cascade;
            create user {self.user_name2} with sysadmin 
            password '{macro.COMMON_PASSWD}';'''
        create_user2 = self.sh_pri.execut_db_sql(user2,
                                                 dbname=f'{self.db_name2}')
        self.log.info(create_user2)
        self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG, create_user2,
                      '执行失败' + text)

        text = '-----step5:兼容数据库1中创建表,插入数据,创建存储过程;' \
               'expect:创建表成功，插入数据成功，创建存储过程成功-----'
        self.log.info(text)

        tab = f'''drop table if exists {self.table};
            create table {self.table}(id int,name varchar(100));
            insert into {self.table} values(generate_series(1,10000),
            'dump_'||generate_series(1,10000))'''
        self.log.info(tab)
        create_tab = self.sh_pri.execut_db_sql(tab,
                                               dbname=f'''{self.db_name1}''')
        self.log.info(create_tab)

        procedure = f'''create or replace procedure {self.procedure}(n int)
            as
            begin
            repeat
                insert into {self.table} values(n,n*2);
                n:=n+1;
                until n>10 end repeat;
            end;'''
        self.log.info(procedure)
        create_pro = self.sh_pri.execut_db_sql(procedure,
                                               dbname=f'''{self.db_name1}''')
        self.log.info(create_pro)

        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, create_tab,
                      '执行失败' + text)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, create_tab,
                      '执行失败' + text)
        self.assertIn(self.constant.CREATE_PROCEDURE_SUCCESS_MSG, create_pro,
                      '执行失败' + text)

        text = '-----step6:执行gs_dump备份,备份用户1,备份库1,备份格式为自定义归档格式;' \
               'expect:备份成功-----'
        self.log.info(text)

        dump = f'''source {macro.DB_ENV_PATH};
            gs_dump {self.db_name1} -p {self.user_node.db_port} \
            -U {self.user_name1} -W {macro.COMMON_PASSWD} \
            -f {self.back_path} -F c'''
        self.log.info(dump)
        dump_res = self.user_node.sh(dump).result()
        self.log.info(dump_res)
        self.assertIn(f'dump database {self.db_name1} successfully', dump_res,
                      '执行失败' + text)

        text = f'''-----step7:执行gs_restore恢复,恢复库2;expect:恢复成功-----'''
        self.log.info(text)

        restore = f'''source {macro.DB_ENV_PATH};
            gs_restore -d {self.db_name2} -p {self.user_node.db_port} \
            -W {macro.COMMON_PASSWD} {self.back_path} '''
        self.log.info(restore)
        restore_res = self.user_node.sh(restore).result()
        self.log.info(restore_res)
        self.assertIn(f'restore operation successful', restore_res,
                      '执行失败' + text)

    def tearDown(self):
        text = '-----step8:清理环境;expect:清理成功-----'
        self.log.info(text)

        clear = f'''drop database {self.db_name1};
            drop database {self.db_name2};
            drop user {self.user_name1} cascade;
            drop user {self.user_name2} cascade;'''
        self.log.info(clear)
        clear_res = self.sh_pri.execut_db_sql(clear, dbname='postgres')
        self.log.info(clear_res)

        rm_file = f'''rm -rf {self.back_path};ls {macro.DB_INSTANCE_PATH}'''
        self.log.info(rm_file)
        rm_file_res = self.user_node.sh(rm_file).result()
        self.log.info(rm_file_res)

        self.assertNotIn('gs_dump_0130.dmp', rm_file_res, '清理文件失败')
        self.assertEqual(clear_res.count(self.constant.DROP_DATABASE_SUCCESS),
                         2, '执行失败' + text)
        self.assertEqual(clear_res.count(self.constant.DROP_ROLE_SUCCESS_MSG),
                         2, '执行失败' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
